package com.tulele.vtool.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tulele.vtool.config.AliyunOSSConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Component
public class AliyunOssClientUtil {

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    public static AliyunOssClientUtil aliyunOssClientUtil;

    @PostConstruct
    public void init() {
        aliyunOssClientUtil = this;
    }

//    public static OSS getOSSClient(){
//        if (client == null) {
//            synchronized (AliyunOssClientUtil.class){
//                if (client == null) {
//                    client = new OSSClientBuilder().build(aliyunOssClientUtil.aliyunOSSConfig.getEndpoint(), aliyunOssClientUtil.aliyunOSSConfig.getAccessKeyId(), aliyunOssClientUtil.aliyunOSSConfig.getAccessKeySecret());
//                }
//            }
//        }
//        return client;
//    }

    /**
     * 获取OSSClient实例
     *
     * @return
     */
    private static OSS getOSSClient() {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssClientUtil.aliyunOSSConfig.getEndpoint(), aliyunOssClientUtil.aliyunOSSConfig.getAccessKeyId(), aliyunOssClientUtil.aliyunOSSConfig.getAccessKeySecret());
        return ossClient;
    }

    /**
     * 上传用户二维码图片
     *
     * @param file
     * @param key
     * @return
     * @throws IOException
     */
    public static String uploadFileByMultipartFile(MultipartFile file, String key) throws IOException {
        getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, file.getInputStream());
        getOSSClient().shutdown();
        return key;
    }

    //文件流上传
    public static void uploadFileByLocalFile(File file, String key) {
        getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, file);
        getOSSClient().shutdown();
    }

    //URL上传
    public static void uploadFileByFileUrl(String fileUrl, String key) {
        // 上传网络流。
        InputStream inputStream = null;
        try {
            inputStream = new URL(fileUrl).openStream();

            getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 关闭OSSClient。
        getOSSClient().shutdown();
    }

    public static String uploadFileByFileUrl2(String urlStr) {
        String ossImgUrl = "";
        HttpURLConnection connection = null;
        URL url = null;
        String suffix = null;

        try {
            url = new URL(urlStr);

            connection = (HttpURLConnection) url.openConnection();

            connection.setInstanceFollowRedirects(true);
            connection.setUseCaches(true);

            suffix = MIMEType.getSuffix(connection.getContentType());
            String strDate = DateUtil.getFormatDate("yyyyMMdd", new Date());
            String filePath = "headImgs/" + strDate + "/" + UUID.randomUUID() + suffix;
            uploadFileByFileUrl(urlStr, filePath);
            ossImgUrl = "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/" + filePath;

        } catch (Exception e) {
            ossImgUrl = urlStr;
        }
        return ossImgUrl;
    }

    //把文章中所有的图片 的路径做 处理，取按比例缩小 的图片
    public static String setImgLoadSize(String articleContent) {

        String returnArticleContent = "";
        try {

            Document document = null;
            document = Jsoup.parse(articleContent);

            Elements imgElements = document.select("img");

            for (Element img : imgElements) {
                String src = "";
                String osspar = SysConstant.OSS_PAR; //宽度固定480，按比例缩小，https://help.aliyun.com/document_detail/44688.htm?spm=a2c4g.11186623.0.0.1a331e4frjuQxA#concept-hxj-c4n-vdb
                if (img.attr("src") != null && !img.attr("src").contains("x-oss-process")) {
                    src = img.attr("src");
                    if (src.contains("?")) {
                        src = src + "&" + osspar;
                    } else {
                        src = src + "?" + osspar;
                    }
                    img.attr("src", src);
                }
            }
            returnArticleContent = document.body().html();
        } catch (Exception e) {
            returnArticleContent = articleContent;
        }
        return returnArticleContent;
    }

    //保存文章时，去掉 图片中的 oss 压缩参数
    public static String clearImgUrlPAR(String articleContent) {

        String returnArticleContent = "";
        try {

            Document document = null;
            document = Jsoup.parse(articleContent);

            Elements imgElements = document.select("img");

            for (Element img : imgElements) {
                String src = "";
                if (img.attr("src") != null && img.attr("src").contains("x-oss-process")) {
                    src = img.attr("src");
                    src = src.substring(0, src.indexOf("?"));
                    img.attr("src", src);
                }
            }
            returnArticleContent = document.body().html();
        } catch (Exception e) {
            returnArticleContent = articleContent;
        }
        return returnArticleContent;
    }

    /**
     * 网络URL上传
     *
     * @param dataSrc
     * @param key
     */
    public static void uploadFileByUrl(String dataSrc, String key) {
        InputStream inStream = null;
        try {
            HttpURLConnection webConn = null;
            //获取视频链接
            URL webUrl = new URL(dataSrc);
            //打开链接
            webConn = (HttpURLConnection) webUrl.openConnection();
            //设置请求方式为"GET"
            webConn.setRequestMethod("GET");
            //建立连接的超时时间
            webConn.setConnectTimeout(10 * 1000);
            //传递数据的超时时间
            webConn.setReadTimeout(10 * 1000);
            //通过输入流获取数据
            inStream = webConn.getInputStream();

            getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, inStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            getOSSClient().shutdown();// 关闭OSSClient。
        }
    }
}
